package com.iflytek.cosmo.ocr.common.core.station;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.iflytek.cosmo.ocr.common.core.task.RecognizedTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2019/11/21 11:16
 */
public abstract class AbstractStation {
    private static final Logger logger = LoggerFactory.getLogger(AbstractStation.class);

    /**
     * 下一个工作台
     */
    protected AbstractStation nextStation;

    private final ThreadPoolExecutor threadPool;

    private String threadGroupName;

    protected AbstractStation(int capacity, int queueSize, final String threadNamePrefix) {
        this.threadGroupName = threadNamePrefix;

        threadPool = new ThreadPoolExecutor(capacity, capacity, 0, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(queueSize),
                new ThreadFactoryBuilder().setDaemon(false).setNameFormat(threadNamePrefix + "-%d")
                                          .setUncaughtExceptionHandler(
                                                  (t, e) -> logger.error("异步处理线程 " + t + " 抛出异常", e)).build(),
                new ThreadPoolExecutor.CallerRunsPolicy());
    }

    /**
     * 添加任务
     *
     * @param task
     */
    public void add(RecognizedTask task) {
        logger.debug("向{}线程池提交任务, 当前池内任务数量为: {}", threadGroupName, threadPool.getQueue().size());
        threadPool.submit(createWorker(task));
    }

    public abstract Runnable createWorker(RecognizedTask task);

    public abstract void setNextStation(AbstractStation station);
}
